package com.arpa.oms.controller;

import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsReceivableDTO;
import com.arpa.oms.domain.dto.OmsSettlementEditDTO;
import com.arpa.oms.domain.entity.OmsReceivable;
import com.arpa.oms.domain.enums.PayableAndReceivableStatusEnum;
import com.arpa.oms.domain.vo.OmsReceivableVO;
import com.arpa.oms.service.IOmsReceivableService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

import static com.arpa.oms.domain.enums.PayableAndReceivableStatusEnum.NEWS;
import static com.arpa.oms.domain.enums.PayableAndReceivableStatusEnum.PENDING;


/**
 * <p>
 * OMS收款单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "OMS收款单")
@RestController
@RequestMapping(value = "/omsReceivable", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class OmsReceivableController {

    @Resource
    private RedissonClient redissonClient;
    private final IOmsReceivableService iOmsReceivableService;

    public OmsReceivableController(IOmsReceivableService iOmsReceivableService) {
        this.iOmsReceivableService = iOmsReceivableService;
    }

    /**
     * 获取 OMS收款单 列表
     *
     * @param omsReceivableDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS收款单 列表", notes = "获取 OMS收款单 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsReceivableVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsReceivableDTO omsReceivableDTO, HttpServletRequest request) {
        try {
            omsReceivableDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            OmsReceivableVO omsReceivableVOSum = iOmsReceivableService.queryListSum(omsReceivableDTO);
            List<OmsReceivableVO> omsReceivableVOList = iOmsReceivableService.queryList(omsReceivableDTO);

            Page returnPage = new Page(omsReceivableDTO.getPageNum(), omsReceivableDTO.getPageSize());
            returnPage.setRecords(omsReceivableVOList);
            returnPage.setTotal(omsReceivableVOSum.getTotal());
            returnPage.setSumObject(omsReceivableVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取OMS收款单详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取OMS收款单详情", notes = "获取OMS收款单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "OMS收款单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsReceivable.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result omsReceivable(@PathVariable String code, HttpServletRequest request) {
        try {
            OmsReceivable entity = iOmsReceivableService.getOmsReceivable(code);
            return Result.ok().data(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }



    /**
     * 保存OMS收款单
     * 只有新增状态下才可以编辑
     *
     * @param entity  OMS收款单
     * @param request
     * @return
     */
    @ApiOperation(value = "保存OMS收款单", notes = "只有新增状态才可以编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PutMapping()
    public Result update(@RequestBody @Validated OmsSettlementEditDTO entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("收款单号不能为空");
        }
        RLock l = null;
        try {
            String code = entity.getCode();
            l = redissonClient.getLock(getCodeKey(code));
            if (l.tryLock()) {
                OmsReceivable omsReceivable = iOmsReceivableService.getOne(new QueryWrapper<OmsReceivable>().lambda()
                        .eq(OmsReceivable::getCode, code).eq(OmsReceivable::getShipmentCode, UserUtil.getShipmentCompanyCode()));
                if (null == omsReceivable) {
                    return Result.error("收款单【" + code + "】修改失败，找不到收款单");
                }

                if (!NEWS.equals(omsReceivable.getStatus())) {
                    return Result.error("收款单【" + code + "】修改失败，当前状态不能修改");
                }
                log.info("修改收款单【{}】获得锁", code);
                entity.setStatus(NEWS);
                iOmsReceivableService.update(entity);
                return Result.ok("收款单修改成功！");
            } else {
                log.error("收款单【{}】修改失败，正在操作中", code);
                return Result.error("收款单【" + code + "】修改失败，正在操作中");
            }
        } catch (Exception ex) {
            log.error(StrConsts.CATCH_MESSAGE, ex);
            return Result.error(ex.getMessage());
        } finally {
            try {
                if (null != l && l.isLocked()) {
                    l.unlock();
                }
            } catch (Exception e) {
                log.error("释放锁失败！！", e);
            }
        }
    }

    /**
     * 提交收款单
     *
     * @param entity  收款单
     * @param request
     * @return
     */
    @ApiOperation(value = "提交收款单 ", notes = "提交收款单更改为待审核状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PostMapping("/submit")
    public Result submit(@RequestBody @Validated OmsSettlementEditDTO entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("收款单号不能为空");
        }
        RLock l = null;
        try {
            String code = entity.getCode();
            l = redissonClient.getLock(getCodeKey(code));
            if (l.tryLock()) {
                OmsReceivable omsReceivable = iOmsReceivableService.getOne(new QueryWrapper<OmsReceivable>().lambda().eq(OmsReceivable::getCode, code).eq(OmsReceivable::getShipmentCode, UserUtil.getShipmentCompanyCode()));
                if (null == omsReceivable) {
                    return Result.error("收款单【" + code + "】提交失败，找不到收款单");
                }
                if (!NEWS.equals(omsReceivable.getStatus())) {
                    return Result.error("收款单【" + code + "】提交失败，当前状态不能提交");
                }
                log.info("提交收款单【{}】获得锁", code);

                entity.setStatus(PENDING);
                iOmsReceivableService.update(entity);
                return Result.ok("收款单提交成功！");
            } else {
                log.error("收款单【{}】提交失败，正在操作中", code);
                return Result.error("收款单【" + code + "】提交失败，正在操作中");
            }
        } catch (Exception ex) {
            log.error(StrConsts.CATCH_MESSAGE, ex);
            return Result.error(ex.getMessage());
        } finally {
            try {
                if (null != l && l.isLocked()) {
                    l.unlock();
                }
            } catch (Exception e) {
                log.error("释放锁失败！！", e);
            }
        }
    }


    /**
     * 删除OMS收款单
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "删除OMS收款单 ", notes = "删除OMS收款单", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "收款单号", paramType = "path", dataType = "String"),
    })
    @NeedLogin
    @DeleteMapping(value = "/{code}")
    public Result delete(@PathVariable String code, HttpServletRequest request) {
        try {
            iOmsReceivableService.removeByCode(code);
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收款单审核
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "收款单审核", notes = "收款单审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "收款单号", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "审核结果: PASS（通过）。NO_PASS（不通过）", required = true, paramType = "query", dataType = "Integer", defaultValue = "1"),
            @ApiImplicitParam(name = "verifyOpinion", value = "审核意见", required = false, paramType = "query", dataType = "String"),
    })
    @NeedLogin
    @PutMapping("/approve/{code}")
    public Result approveFail(@PathVariable String code, @RequestParam("status") PayableAndReceivableStatusEnum status, @RequestParam(value = "verifyOpinion",defaultValue = "") String verifyOpinion, HttpServletRequest request) {
        try {
            if(StringUtils.isBlank(code)){
                return Result.error("code不能为空");
            }
            boolean updateNum = iOmsReceivableService.approve(code,status,verifyOpinion);
            if(updateNum) {
                return Result.ok("收款单审核成功！");
            }else{
                return Result.error("收款单审核失败！");
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    private String getCodeKey(String code) {
        return String.format("OmsReceivable-op-%s", code);
    }
}
